package com.tongxin.van.frameworkcanary.utils;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.blankj.utilcode.util.SPUtils;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * author: VanyLiu
 * email: 13212674795@163.com
 * description:搜素字段持久化工具类
 *
**/

public class SearchHistoryUtils {

    /**
     * 保存关键字
     *
     * @param searchKey 搜素关键字
     */
    public static void saveKey(String searchKey) {
        //空格处理
        searchKey = searchKey.trim();
        if (TextUtils.isEmpty(searchKey)) {
            return;
        }
        List<String> historyList = getHistoryKeys();

        //删除相同的关键字
        for (int i = 0; i < historyList.size(); i++) {
            if (historyList.get(i).equals(searchKey)) {
                historyList.remove(i);
                i--;
            }
        }
        //添加关键字
        historyList.add(0,searchKey);
        String searchHistory = "";
        for (String str : historyList) {
            searchHistory = searchHistory + ";" + str;
        }
        //保存到SP中
        SPUtils.getInstance().put("searchHistory", searchHistory);
    }

    /**
     * 获取历史关键字
     */
    @NonNull
    public static List<String> getHistoryKeys() {
        //获取原有历史记录
        String history = SPUtils.getInstance().getString("searchHistory");
        String[] historyAry = history.split(";");
        List<String> list = new ArrayList<>();
        for (int i = 0; i < historyAry.length; i++) {
            if (!TextUtils.isEmpty(historyAry[i])) {
                list.add(historyAry[i]);
            }
        }
        return list;
    }

    /**
     * 清空SP保存的关键字
     */
    public static void emptyKey() {
        SPUtils.getInstance().put("searchHistory", "");
    }
}
